<template>
  <div class="seller-qualification-container">
    <div class="header-section">
      <h2 class="page-title">卖家资质审核</h2>
      <el-alert
        class="info-alert"
        title="审核说明：请仔细查看卖家提交的资质材料，确认无误后进行审核操作"
        type="info"
        show-icon
        :closable="false"
      />
    </div>
    
    <!-- 搜索和筛选区域 -->
<el-card class="filter-card" shadow="hover">
  <template #header>
    <div class="card-header">
      <span>筛选条件</span>
    </div>
  </template>
  <el-form :inline="true" :model="searchForm" class="filter-form">
    <el-row :gutter="10">
      <el-col :span="14">
        <el-form-item label="审核状态" class="status-form-item">
          <el-select 
            v-model="searchForm.auditStatus" 
            placeholder="请选择审核状态" 
            clearable
            class="filter-select">
            <el-option label="待审核" :value="0"></el-option>
            <el-option label="审核通过" :value="1"></el-option>
            <el-option label="审核不通过" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <div class="button-group">
          <el-button type="primary" @click="fetchData" icon="Search">查询</el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
        </div>
      </el-col>
    </el-row>
  </el-form>
</el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>资质列表</span>
          <div class="header-actions">
            <el-badge :value="pagination.total" class="total-badge">
              <el-button type="info" plain>总计</el-button>
            </el-badge>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="tableData" 
        v-loading="loading" 
        border
        stripe
        class="qualification-table"
        highlight-current-row
      >
        <el-table-column prop="qualificationId" label="资质ID" width="100" align="center"></el-table-column>
        <el-table-column prop="userId" label="用户ID" width="100" align="center"></el-table-column>
        <el-table-column label="卖家类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.sellerType === 0 ? 'primary' : 'success'" effect="dark">
              {{ scope.row.sellerType === 0 ? '个人卖家' : '企业卖家' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资质材料" width="200" align="center">
          <template #default="scope">
            <div class="material-preview" v-if="scope.row.sellerType === 0">
              <el-popover placement="top" trigger="hover">
                <template #reference>
                  <el-image 
                    :src="scope.row.idCardFront" 
                    fit="cover" 
                    class="material-thumb"
                  />
                </template>
                <el-image 
                  :src="scope.row.idCardFront" 
                  fit="contain" 
                  class="material-large"
                />
              </el-popover>
              <el-popover placement="top" trigger="hover">
                <template #reference>
                  <el-image 
                    :src="scope.row.idCardBack" 
                    fit="cover" 
                    class="material-thumb"
                  />
                </template>
                <el-image 
                  :src="scope.row.idCardBack" 
                  fit="contain" 
                  class="material-large"
                />
              </el-popover>
            </div>
            <div class="material-preview" v-else>
              <el-popover placement="top" trigger="hover">
                <template #reference>
                  <el-image 
                    :src="scope.row.businessLicense" 
                    fit="cover" 
                    class="material-thumb"
                  />
                </template>
                <el-image 
                  :src="scope.row.businessLicense" 
                  fit="contain" 
                  class="material-large"
                />
              </el-popover>
              <el-popover placement="top" trigger="hover">
                <template #reference>
                  <el-image 
                    :src="scope.row.legalIdCardFront" 
                    fit="cover" 
                    class="material-thumb"
                  />
                </template>
                <el-image 
                  :src="scope.row.legalIdCardFront" 
                  fit="contain" 
                  class="material-large"
                />
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.auditStatus === 0" type="warning" effect="dark">待审核</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 1" type="success" effect="dark">审核通过</el-tag>
            <el-tag v-else type="danger" effect="dark">审核不通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditRemark" label="审核备注" min-width="150"></el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180" align="center">
          <template #default="scope">
            {{ scope.row.applyTime ? formatTime(scope.row.applyTime) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="auditTime" label="审核时间" width="180" align="center">
          <template #default="scope">
            {{ scope.row.auditTime ? formatTime(scope.row.auditTime) : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                size="small" 
                type="primary" 
                :disabled="scope.row.auditStatus !== 0"
                @click="handleAudit(scope.row, 1)"
                icon="Check"
              >
                通过
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                :disabled="scope.row.auditStatus !== 0"
                @click="handleAudit(scope.row, 2)"
                icon="Close"
              >
                拒绝
              </el-button>
              <el-button 
                size="small" 
                @click="viewDetail(scope.row)"
                icon="View"
              >
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        class="pagination"
        background
      >
      </el-pagination>
    </el-card>
    
    <!-- 审核对话框 -->
    <el-dialog 
      title="审核资质" 
      v-model="auditDialogVisible" 
      width="500px"
      class="audit-dialog"
    >
      <el-form :model="auditForm" ref="auditFormRef" label-width="100px">
        <el-form-item label="资质ID">
          <el-input v-model="auditForm.qualificationId" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="currentRow.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="卖家类型">
          <el-input :value="currentRow.sellerType === 0 ? '个人卖家' : '企业卖家'" disabled></el-input>
        </el-form-item>
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input 
            v-model="auditForm.auditRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核备注（拒绝时必填）"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 详情对话框 -->
    <el-dialog 
      title="资质详情" 
      v-model="detailDialogVisible" 
      width="700px"
      class="detail-dialog"
    >
      <el-scrollbar max-height="500px">
        <el-form label-width="120px" class="detail-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="资质ID：">
                {{ currentRow.qualificationId }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户ID：">
                {{ currentRow.userId }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="卖家类型：">
                <el-tag :type="currentRow.sellerType === 0 ? 'primary' : 'success'" effect="dark">
                  {{ currentRow.sellerType === 0 ? '个人卖家' : '企业卖家' }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请时间：">
                {{ currentRow.applyTime ? formatTime(currentRow.applyTime) : '' }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="审核状态：">
                <el-tag v-if="currentRow.auditStatus === 0" type="warning" effect="dark">待审核</el-tag>
                <el-tag v-else-if="currentRow.auditStatus === 1" type="success" effect="dark">审核通过</el-tag>
                <el-tag v-else type="danger" effect="dark">审核不通过</el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核时间：">
                {{ currentRow.auditTime ? formatTime(currentRow.auditTime) : '' }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="审核备注：">
            {{ currentRow.auditRemark || '-' }}
          </el-form-item>
          
          <el-divider>资质材料</el-divider>
          <div v-if="currentRow.sellerType === 0" class="materials-section">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身份证正面：">
                  <el-image 
                    :src="currentRow.idCardFront" 
                    :preview-src-list="[currentRow.idCardFront]" 
                    fit="contain" 
                    class="material-full"
                    preview-teleported
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证反面：">
                  <el-image 
                    :src="currentRow.idCardBack" 
                    :preview-src-list="[currentRow.idCardBack]" 
                    fit="contain" 
                    class="material-full"
                    preview-teleported
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-else class="materials-section">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="营业执照：">
                  <el-image 
                    :src="currentRow.businessLicense" 
                    :preview-src-list="[currentRow.businessLicense]" 
                    fit="contain" 
                    class="material-full"
                    preview-teleported
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人身份证正面：">
                  <el-image 
                    :src="currentRow.legalIdCardFront" 
                    :preview-src-list="[currentRow.legalIdCardFront]" 
                    fit="contain" 
                    class="material-full"
                    preview-teleported
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="法人身份证反面：">
                  <el-image 
                    :src="currentRow.legalIdCardBack" 
                    :preview-src-list="[currentRow.legalIdCardBack]" 
                    fit="contain" 
                    class="material-full"
                    preview-teleported
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import httpInstance from '@/utils/http'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  auditStatus: null
})

// 分页信息
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 统计数据
const stats = computed(() => {
  const pending = tableData.value.filter(item => item.auditStatus === 0).length
  const approved = tableData.value.filter(item => item.auditStatus === 1).length
  const rejected = tableData.value.filter(item => item.auditStatus === 2).length
  return { pending, approved, rejected }
})

// 审核对话框
const auditDialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 当前行数据
const currentRow = ref({})

// 审核表单
const auditForm = reactive({
  qualificationId: null,
  auditStatus: 1,
  auditRemark: '',
  userId: null
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time.replace('T', ' '));
  if (isNaN(date.getTime())) return '';
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await httpInstance.post(
      `/eduservice/sellerQualification/page/${pagination.pageNo}/${pagination.pageSize}`,
      {
        auditStatus: searchForm.auditStatus
      }
    )
    
    tableData.value = response.data.list || []
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.auditStatus = null
  fetchData()
}

// 处理分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val) => {
  pagination.pageNo = val
  fetchData()
}

// 处理审核
const handleAudit = (row, status) => {
  currentRow.value = row
  auditForm.qualificationId = row.qualificationId
  auditForm.auditStatus = status
  auditForm.auditRemark = ''
  auditForm.userId = row.userId
  auditDialogVisible.value = true
}

// 提交审核
const submitAudit = async () => {
  if (auditForm.auditStatus === 2 && !auditForm.auditRemark.trim()) {
    ElMessage.warning('审核不通过时必须填写备注')
    return
  }
  
  try {
    await httpInstance.put('/eduservice/sellerQualification/updateAudit', {
      qualificationId: auditForm.qualificationId,
      auditStatus: auditForm.auditStatus,
      auditRemark: auditForm.auditRemark,
      userId: auditForm.userId
    })
    ElMessage.success('审核成功')
    auditDialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('审核失败')
    console.error(error)
  }
}

// 查看详情
const viewDetail = (row) => {
  currentRow.value = row
  detailDialogVisible.value = true
}

// 初始化数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.filter-select {
  width: 180px;
}
.seller-qualification-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header-section {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.info-alert {
  border-radius: 8px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.filter-form {
  margin-bottom: -20px;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.pending-card {
  background: linear-gradient(135deg, #fff7e6 0%, #ffeed6 100%);
  border-left: 4px solid #faad14;
}

.approved-card {
  background: linear-gradient(135deg, #f6ffed 0%, #eaffdb 100%);
  border-left: 4px solid #52c41a;
}

.rejected-card {
  background: linear-gradient(135deg, #fff2f0 0%, #ffebe6 100%);
  border-left: 4px solid #ff4d4f;
}

.stat-content {
  text-align: center;
  padding: 15px 0;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.table-card {
  border-radius: 8px;
  overflow: hidden;
}

.qualification-table {
  margin-bottom: 20px;
}

.material-preview {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.material-thumb {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.material-thumb:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.material-large {
  width: 300px;
  height: 200px;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  justify-content: center;
}

.material-full {
  width: 100%;
  max-width: 250px;
  height: 150px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.materials-section {
  margin-top: 10px;
}

.detail-form {
  padding-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

.total-badge :deep(.el-badge__content) {
  background-color: #909399;
}

.audit-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.detail-dialog :deep(.el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}

@media (max-width: 768px) {
  .seller-qualification-container {
    padding: 10px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .material-thumb {
    width: 60px;
    height: 45px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>